<template>
  <div
    class="popup"
    v-if="isClose"
    :style="{ top: `${position.y}px`, left: `${position.x}px` }"
  >
    <div class="popup-btn" @mousedown.prevent="onMouseDown">
      <el-button
        @click="showContent('事件信息')"
        :class="{ active: currentContent === '事件信息' }"
        >事件信息</el-button
      >
      <el-button
        @click="showContent('统计图')"
        :class="{ active: currentContent === '统计图' }"
        >统计图</el-button
      >
      <el-button
        @click="showContent('热力图')"
        :class="{ active: currentContent === '热力图' }"
        >热力图</el-button
      >
      <el-button class="close-btn" @click="$emit('close')">x</el-button>
    </div>
    <!-- 事件信息 -->
    <div class="popup-table" v-if="currentContent === '事件信息'">
      <el-table :data="pageData" border style="width: 100%">
        <el-table-column prop="事件编号" label="事件编号" width="160" />
        <el-table-column prop="事件类型" label="事件类型" width="100" />
        <el-table-column prop="事件等级" label="事件等级" width="90" />
        <el-table-column prop="发生时间" label="发生时间" width="160" />
        <el-table-column prop="发生地点" label="发生地点" width="200" />
        <el-table-column prop="车牌号" label="车牌号" width="130" />
        <el-table-column prop="驾驶员" label="驾驶员" width="90" />
        <el-table-column prop="处理状态" label="处理状态" width="90" />
      </el-table>
      <el-pagination
        @current-change="handlePageChange"
        :page-size="5"
        layout="prev, pager, next"
        :total="evnetInfo.length"
      />
    </div>

    <!-- 统计图 -->
    <div v-if="currentContent === '统计图'" class="chart-container">
      <v-chart
        :option="categoryOption"
        style="width: 100%; height: 300px"
      ></v-chart>
      <v-chart
        :option="categoryOptionLevel"
        style="width: 100%; height: 300px"
      ></v-chart>
    </div>
    <!-- 热力图 -->
    <div v-if="currentContent === '热力图'" class="heatmap-container">
      <div class="heatmap-switch">
        设置热点图：
        <el-switch v-model="heatmapEnabled" @change="toggleHeatmap"></el-switch>
      </div>
      <div class="heatmap-parameters">
        <div class="heatmap-setting">
          <label>热点半径(radius size): </label>
          <input
            type="range"
            id="radius"
            min="1"
            max="50"
            step="1"
            v-model="heatmapRadius"
            @input="updateHeatmapRadius(heatmapRadius)"
          />
        </div>
        <div class="heatmap-setting">
          <label>模糊尺寸(blur size):</label>
          <input
            type="range"
            id="blur"
            min="1"
            max="50"
            step="1"
            v-model="heatmapBlur"
            @input="updateHeatmapBlur(heatmapBlur)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch, getCurrentInstance } from "vue";

let map; //接收地图实例
//设置热力图参数
const heatmapRadius = ref(10);
const heatmapBlur = ref(1);
//热力图开关
const heatmapEnabled = ref(false);
//用于存储处理后的feature数据
let evnetInfo = ref([]);
//接收父组件传递的feature数据
const props = defineProps({
  featuresInfo: {
    type: Array,
    default: () => [],
  },
  isClose: {
    type: Boolean,
  },
});

const currentContent = ref("事件信息"); //当前显示的内容，默认显示事件信息
// const position = ref({ x: 964, y: 631 }); // 初始化位置
const position = ref({
  x: window.innerWidth * 0.5, // 设置x为50%的宽度
  y: window.innerHeight * 0.5, // 设置y为50%的高度
});
let isDragging = false; // 拖拽状态
let startDraggingPosition = { x: 0, y: 0 }; // 开始拖拽时的位置

onMounted(() => {
  //处理feature数据
  evnetInfo.value = props.featuresInfo.map((item) => {
    let status;
    switch (item.values_.values_.处理状态) {
      case "2":
        status = "已处理";
        break;
      case "1":
        status = "处理中";
        break;
      case "0":
        status = "未处理";
        break;
      default:
        status = "未知状态"; // 处理未涵盖的情况
    }
    return {
      ...item.values_.values_, // 保留其他的值
      处理状态: status, // 更新处理状态
    };
  });
});

//分页器操作
const page = ref(1);
const handlePageChange = (value) => {
  page.value = value;
};
const pageData = computed(() => {
  const start = (page.value - 1) * 5;
  const end = start + 5;
  return evnetInfo.value.slice(start, end);
});

//向父组件传递关闭事件
const emits = defineEmits(["close"]);

//点击到对应的按钮，显示对应的内容
const showContent = (content) => {
  currentContent.value = content;
};

/* 统计图 */
const categoryOption = ref({}); // 统计图配置项
const categoryData = ref([]); // 事件类型数据
const categoryOptionLevel = ref({}); // 事件等级配置项
const categoryDataLevel = ref([]); // 事件等级数据
const renderCategoryChart = (data) => {
  const _data = data.map((item) => {
    return {
      ...item,
      name: `${item.title} | ${item.value}`,
    };
  });
  categoryOption.value = {
    title: [
      {
        text: "事件类型分析",
        textStyle: {
          fontSize: 14,
          color: "black",
        },
      },
    ],
    //弹窗
    tooltip: {
      formatter(params) {
        const res = `
          ${params.seriesName}<br>
          ${params.marker} ${params.data.title} <br>
          ${params.marker} 次数: ${params.data.value} <br>
        `;
        return res;
      },
    },
    legend: {
      orient: "vertical",
      left: "75%",
      top: "top",
      textStyle: {
        color: "#888",
      },
    },
    series: {
      name: "事件类型",
      type: "pie",
      data: _data,
      center: ["40%", "50%"],
    },
  };
};
const renderCategoryChartLevel = (data) => {
  const _data = data.map((item) => {
    return {
      ...item,
      name: `${item.title} | ${item.value}`,
    };
  });
  categoryOptionLevel.value = {
    title: [
      {
        text: "事件等级分析",
        textStyle: {
          fontSize: 14,
          color: "black",
        },
      },
    ],
    //弹窗
    tooltip: {
      formatter(params) {
        const res = `
          ${params.seriesName}<br>
          ${params.marker} ${params.data.title} <br>
          ${params.marker} 次数: ${params.data.value} <br>
        `;
        return res;
      },
    },
    legend: {
      orient: "vertical",
      left: "75%",
      top: "top",
      textStyle: {
        color: "#888",
      },
    },
    series: {
      name: "事件等级分析",
      type: "pie",
      data: _data,
      center: ["40%", "50%"],
    },
  };
};

onMounted(() => {
  const eventTypes = ["碰撞", "刮擦", "其他", "失火", "翻车", "碾压"];
  const eventLevel = ["轻微事故", "一般事故", "特大事故", "重大事故"];
  categoryData.value = eventTypes.map((type) => ({
    title: type,
    value: evnetInfo.value.filter((item) => item.事件类型 === type).length,
  }));
  categoryDataLevel.value = eventLevel.map((level, index) => ({
    title: level,
    value: evnetInfo.value.filter((item) => item.事件等级 === String(index + 1))
      .length,
  }));
  console.log(categoryDataLevel.value, "categoryData.value");
  renderCategoryChart(categoryData.value);
  renderCategoryChartLevel(categoryDataLevel.value);
});

/* 热力图 */
//创建热力图图层
const heatMapLayer = new ol.layer.Heatmap({
  source: new ol.source.Vector({
    features: props.featuresInfo,
  }),
  blur: 4,
  radius: 8,
  /* weight: function (feature) {
    return feature.get("weight");
  }, */
});

onMounted(() => {
  const { proxy } = getCurrentInstance();
  map = proxy.$map;
});

//更新热力图半径
const updateHeatmapRadius = (radius) => {
  heatMapLayer.setRadius(parseInt(radius));
};
//更新热力图模糊尺寸
const updateHeatmapBlur = (blur) => {
  heatMapLayer.setBlur(parseInt(blur));
};

//切换热力图开关逻辑
const toggleHeatmap = (value) => {
  if (value) {
    map.addLayer(heatMapLayer);
  } else {
    map.removeLayer(heatMapLayer);
  }
};

//写一个事件监听器，当isClose变成false时,清除热力图图层,同时按钮状态变成false
watch(
  () => props.isClose,
  (value) => {
    if (!value) {
      map.removeLayer(heatMapLayer);
      heatmapEnabled.value = false;
    }
  }
);

// 拖拽功能实现
const onMouseDown = (event) => {
  //启动拖拽
  isDragging = true;
  // 计算鼠标相对于弹窗左上角的初始偏移量，并保存。
  // event.clientX 是鼠标相对于浏览器窗口的 x 坐标，
  // position.value.x 是当前弹窗的 x 坐标；
  // 两者相减得到偏移量。
  startDraggingPosition.x = event.clientX - position.value.x;
  startDraggingPosition.y = event.clientY - position.value.y;
  //鼠标移动事件和鼠标松开事件监听器
  document.addEventListener("mousemove", onMouseMove);
  document.addEventListener("mouseup", onMouseUp);
};

const onMouseMove = (event) => {
  if (isDragging) {
    // 计算鼠标相对于弹窗左上角的当前偏移量，并更新弹窗的位置。
    position.value.x = event.clientX - startDraggingPosition.x;
    position.value.y = event.clientY - startDraggingPosition.y;
  }
};

const onMouseUp = () => {
  //停止拖拽
  isDragging = false;
  document.removeEventListener("mousemove", onMouseMove);
  document.removeEventListener("mouseup", onMouseUp);
};
</script>

<style scoped>
.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 居中 */
  width: 1020px;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  z-index: 1000; /* 确保 popup 在最上层 */
}
.popup-btn {
  display: flex;
  margin-bottom: 10px;
}
/* 关闭按钮放在最右边 */
.close-btn {
  margin-left: auto;
}
.active {
  background-color: #409eff;
  color: #fff;
}
.heatmap-switch {
  padding: 20px;
}
.heatmap-setting {
  display: flex;
  margin-bottom: 10px;
  padding: 20px;
}
.heatmap-setting label {
  margin-right: 20px;
}
.chart-container {
  display: flex;
}
</style>
